#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

int main()
{
    //【1】创建无名管道
    int pipefd[2];
    if(pipe(pipefd)== -1)
    {
        perror("fail to pipe");
        exit(-1);
    }
    //【2】创建子进程
    pid_t pid;
    if((pid = fork()) < 0)
    {
        perror("fail to fork");
        exit(-1);
    }
    //父进程负责写操作
    if(pid > 0)
    {
        char input[32] = "";
        while(1)
        {
            fgets(input,sizeof(input),stdin);
            input[strlen(input)-1] = '\0';
            if(write(pipefd[1],input,sizeof(input))==-1)
            {
                perror("fail to write");
                exit(-1);
            }
        }
    }
    //子进程负责读操作
    else
    {
        while(1)
        {
            char buf[32] = "";
            ssize_t bytes = 0;
            if((bytes = read(pipefd[0],buf,32))==-1)
            {
                perror("fail to read");
                exit(-1);
            }
            printf("from parent:%s\n",buf);
        }
    }
    return 0;
}